package com.mysoft.gfyx.workbench.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysoft.framework.common.util.MappingUtil;
import com.mysoft.framework.modeling.dto.OptionItem;
import com.mysoft.gfyx.common.time.TimeService;
import com.mysoft.gfyx.workbench.dao.PermTenantProfitDao;
import com.mysoft.gfyx.workbench.dao.PermTenantProvinceDao;
import com.mysoft.gfyx.workbench.dao.entity.PermTenantProfit;
import com.mysoft.gfyx.workbench.dao.entity.PermTenantProvince;
import com.mysoft.gfyx.workbench.service.ProfitProvinceService;
import com.mysoft.gfyx.workbench.service.ProfitService;
import com.mysoft.gfyx.workbench.service.dto.GetProfitProvinceDataDto;
import com.mysoft.gfyx.workbench.service.dto.GetProfitProvinceNumDataDto;
import com.mysoft.gfyx.workbench.service.dto.SaveProfitProvinceDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Slf4j
public class ProfitProvinceServiceImpl implements ProfitProvinceService {

    @Value("${product-profit.market-report}")
    private String productProfitMarketReport;

    @Value("${product-profit.clue-radar-nationwide}")
    private String productProfitClueRadarNationwide;

    @Value("${product-profit.clue-radar-province}")
    private String productProfitClueRadarProvince;

    @Autowired
    private PermTenantProfitDao permTenantProfitDao;

    @Autowired
    private TimeService timeService;

    @Autowired
    private PermTenantProvinceDao permTenantProvinceDao;

    public void resetModifiedDate() {
        QueryWrapper<PermTenantProvince> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("__IsDeleted", 0);

        String oneYearAgo = timeService.getYearsAgo(1, new Date(), "yyyy-MM-dd HH:mm:ss");
        PermTenantProvince permTenantProvince = new PermTenantProvince();
        permTenantProvince.setLatestModificationDate(oneYearAgo);
        permTenantProvinceDao.update(permTenantProvince, queryWrapper);
    }

    public GetProfitProvinceNumDataDto getProfitProvinceNum() {
        GetProfitProvinceNumDataDto getProfitProvinceNumDataDto = new GetProfitProvinceNumDataDto();
        QueryWrapper<PermTenantProfit> queryWrapper = new QueryWrapper<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        queryWrapper.ge("EffectiveEndTime", sdf.format(new Date()));
        queryWrapper.le("EffectiveStartTime", sdf.format(new Date()));
        List<PermTenantProfit> permTenantProfitList = permTenantProfitDao.selectList(queryWrapper);
        AtomicReference<Integer> num = new AtomicReference<>(0);
        getProfitProvinceNumDataDto.setProvinceNumType(ProvinceNumType.Province.toString());
        permTenantProfitList.forEach(m -> {
            //只有线索雷达是全国权益，其他的都是省份权益（如线索雷达省份版，市场洞察）
            if (m.getProductCode().equals(ProfitService.Product.ClueRadarNationwide.toString())) {
                getProfitProvinceNumDataDto.setProvinceNumType(ProvinceNumType.NationWide.toString());
            }

            if (m.getProductCode().equals(ProfitService.Product.ClueRadarProvince.toString())) {//线索雷达省份版，需要将省份数量汇总
                num.updateAndGet(v -> v + m.getNumber().intValue());
            }
        });
        getProfitProvinceNumDataDto.setProvinceNum(num.get().intValue());
        return getProfitProvinceNumDataDto;
    }

    public GetProfitProvinceDataDto getProfitProvince() {
        GetProfitProvinceDataDto getProfitProvinceDataDto = new GetProfitProvinceDataDto();
        GetProfitProvinceNumDataDto numDto = this.getProfitProvinceNum();
        getProfitProvinceDataDto.setProvinceNumType(numDto.getProvinceNumType());
        getProfitProvinceDataDto.setProvinceNum(numDto.getProvinceNum());
        //获取省份
        QueryWrapper<PermTenantProvince> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("__IsDeleted", 0);
        queryWrapper.orderByAsc("ProvinceWeight");
        queryWrapper.last("limit " + numDto.getProvinceNum());
        List<PermTenantProvince> permTenantProvinceList = permTenantProvinceDao.selectList(queryWrapper);
        List<OptionItem> items = new ArrayList<>();
        List<String> provinceCodeList = new ArrayList<>();
        if (permTenantProvinceList.size() > 0) {
            permTenantProvinceList.forEach(p -> {
                OptionItem item = new OptionItem();
                item.setValue(p.getProvinceCode());
                item.setText(p.getProvinceName());
                items.add(item);
                provinceCodeList.add(p.getProvinceCode());
                getProfitProvinceDataDto.setLastSettingTime(p.getLatestModificationDate());
            });
        }
        getProfitProvinceDataDto.setUsedNum(permTenantProvinceList.size());
        getProfitProvinceDataDto.setAvailableNum(numDto.getProvinceNum() - permTenantProvinceList.size());
        getProfitProvinceDataDto.setProvinceList(items);
        getProfitProvinceDataDto.setProvinceCodeList(provinceCodeList);
        return getProfitProvinceDataDto;
    }

    public void saveProfitProvince(SaveProfitProvinceDto dto) {
        SimpleDateFormat normalFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String latestModificationDate = normalFormater.format(new Date());
        List<String> provinceCode = new ArrayList<>();
        //获取以provinceCode为key，其他属性或者对应对象为value的Map集合
        Map<String, SaveProfitProvinceDto.ProvinceListIndex> provinceListMap = new HashMap<>();
        AtomicReference<Integer> index = new AtomicReference<>(0);
        dto.getProvinceList().forEach(m -> {
            if (!provinceListMap.containsKey(m.getValue())) {
                SaveProfitProvinceDto.ProvinceListIndex newItem = MappingUtil.getSimpleMapperFacade().map(m, SaveProfitProvinceDto.ProvinceListIndex.class);
                newItem.setIndex(index.get());
                provinceListMap.put(m.getValue(), newItem);
            }
            index.set(index.get() + 1);
            provinceCode.add(m.getValue());
        });
        //更新
        QueryWrapper<PermTenantProvince> queryWrapperUpdate = new QueryWrapper<>();
        List<PermTenantProvince> permTenantProvinceUpdate = permTenantProvinceDao.selectList(queryWrapperUpdate);
        List<String> provinceCodeExist = new ArrayList<>();//已经存在的省份
        permTenantProvinceUpdate.forEach(m -> {
            if (provinceCode.contains(m.getProvinceCode())) {
                m.setProvinceWeight(provinceListMap.get(m.getProvinceCode()).getIndex());
                m.set__IsDeleted(0);
            } else {//删除的，将权重调至最小
                m.setProvinceWeight(9999);
                m.set__IsDeleted(1);
            }
            m.setLatestModificationDate(latestModificationDate);
            provinceCodeExist.add(m.getProvinceCode());
        });
        if (permTenantProvinceUpdate.size() > 0) {
            permTenantProvinceDao.updateBatchByIdWithDynamicExt(permTenantProvinceUpdate);
        }
        //新增
        List<PermTenantProvince> permTenantProvinceAdd = new ArrayList<>();//新增的省份
        dto.getProvinceList().forEach(m -> {
            if (!provinceCodeExist.contains(m.getValue())) {
                PermTenantProvince permTenantProvinceNew = new PermTenantProvince();
                permTenantProvinceNew.setProvinceCode(m.getValue());
                permTenantProvinceNew.setProvinceName(m.getText());
                permTenantProvinceNew.setProvinceWeight(provinceListMap.get(m.getValue()).getIndex());
                permTenantProvinceNew.setPermTenantProvinceGUID(UUID.randomUUID());
                permTenantProvinceNew.setLatestModificationDate(latestModificationDate);
                permTenantProvinceAdd.add(permTenantProvinceNew);
            }
        });

        if (permTenantProvinceAdd.size() > 0) {
            permTenantProvinceDao.insertBatchWithDynamicExt(permTenantProvinceAdd);
        }

    }
}
